package com.xbongbong.paas.help.subform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.saas.domain.entity.QuotationUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.QuotationTeamEnum;
import com.xbongbong.paas.help.subform.abstracts.AbstractUserTeamTransferSubForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 报价单es和数据库格式转化
 * @author 魏荣杰
 * @date 2020/8/21 16:59
 * @since
 * @version
 */
@Component
public class QuotationTeamTransferSubForm extends AbstractUserTeamTransferSubForm {
    private static final Logger LOG = LoggerFactory.getLogger(QuotationTeamTransferSubForm.class);


    @Override
    public PaasFormDataEntity transferTeamToFormData(UserTeamEntity userTeamEntity) {
        QuotationUserEntity quotationUserEntity = (QuotationUserEntity) userTeamEntity;
        PaasFormDataEntity paasFormDataEntity = createPaasFormDataEntityForUserTeam(userTeamEntity);
        JSONObject teamJson = JSONObject.parseObject(JSON.toJSONString(quotationUserEntity));

        JSONObject data = new JSONObject();
        QuotationTeamEnum[] quotationTeamEnums = QuotationTeamEnum.values();
        for (QuotationTeamEnum quotationTeamEnum : quotationTeamEnums) {
            String dbAttr = quotationTeamEnum.getDbAttr();
            String dataAttr = quotationTeamEnum.getDataAttr();
            Integer fieldType = quotationTeamEnum.getFieldType();
            formatDataForEs(teamJson, data, dbAttr, dataAttr, fieldType);
        }

        paasFormDataEntity.setData(data);

        return paasFormDataEntity;
    }

    @Override
    public UserTeamEntity transferFormDataToTeam(PaasFormDataEntity paasFormDataEntity) {
        JSONObject data = paasFormDataEntity.getData();

        JSONObject dbData = new JSONObject();
        QuotationTeamEnum[] quotationTeamEnums = QuotationTeamEnum.values();
        for (QuotationTeamEnum quotationTeamEnum : quotationTeamEnums) {
            String dbAttr = quotationTeamEnum.getDbAttr();
            String dataAttr = quotationTeamEnum.getDataAttr();
            Integer fieldType = quotationTeamEnum.getFieldType();
            formatDataForDb(data, dbData, dbAttr, dataAttr, fieldType);

        }
        QuotationUserEntity quotationUserEntity = JSON.parseObject(dbData.toJSONString(), QuotationUserEntity.class);
        quotationUserEntity.setAddTime(paasFormDataEntity.getAddTime());
        quotationUserEntity.setUpdateTime(paasFormDataEntity.getUpdateTime());
        quotationUserEntity.setCorpid(paasFormDataEntity.getCorpid());
        quotationUserEntity.setDel(paasFormDataEntity.getDel());
        quotationUserEntity.setId(paasFormDataEntity.getId());

        return quotationUserEntity;
    }
}
